﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：TenantRedisManager.cs
// 功能描述：TongTongMall.MallWeb.Application
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Application.Services;
using TongTongMall.Dependecy;
using TongTongMall.Domain.Repositories.Repositories;
using TongTongMall.Domain.Services;
using TongTongMall.Extensions;
using TongTongMall.MallWeb.Core.Identitys;
using TongTongMall.MallWeb.Core.Tenant.Models;
using TongTongMall.Redis.Cache;
using TongTongMall.Redis.Cache.Configuration;

namespace TongTongMall.MallWeb.Core.Tenant.Services
{
    /// <summary>
    /// 商户redis内结构管理
    /// </summary>
    public class TenantRedisManager : ApplicationService
    {
        private IRedisCache _redisCache;

        /// <summary>
        /// Redis的配置信息
        /// </summary>
        public IRedisConfiguration RedisConfigurationManager { get; set; } = RedisConfiguration.Default;

        private IRepository<Core.Authorization.Client, long> _clientRepository
        {
            get
            {
                return IocManager.Instance.Resolve<IRepository<Core.Authorization.Client, long>>();
            }
        }

        public TenantRedisManager(IRedisCache _redisCache)
        {
            this._redisCache = _redisCache;
        }


        /// <summary>
        /// 获取租户信息
        /// </summary>
        /// <param name="tenantName"></param>
        /// <returns></returns>
        public virtual async Task<TenantInfo> GetTenantInfo(string tenantName)
        {
            if (tenantName.IsNullOrEmpty()) tenantName = Session.TenantName;
            var tenantInfoKey = RedisConfigurationManager.GroupKeys(RedisKeys.Instance.TenantInfo_Key.Item1, $"{tenantName}");
            var model = await _redisCache.GetOrAddAsync(tenantInfoKey, (key) =>
            {
                return Task.Factory.StartNew(() =>
                {
                    return _clientRepository.FirstOrDefault(new { IsActive = true, Name = tenantName });
                });
            }, RedisKeys.Instance.TenantInfo_Key.Item2.ExpireTime);
            return model == null ? default(TenantInfo) : new TenantInfo
            {
                Account = model.Name,
                Secret = model.Secret,
                TenantID = model.Id
            };
        }
    }
}
